package com.magima.core.prompt;

import java.util.HashMap;

public class TreeNode<T> {
	protected HashMap<String, TreeNode<T>> children;
	protected TreeNode<T> parent;
	protected T data;
	public TreeNode(T data) {
        this.data = data;
    }
	public void setData(T data){
		this.data = data;
	}
	public T getData(){
		return data;
	}
	public void addChild(T data, String id){
		synchronized ( this ){
			TreeNode<T> node = new TreeNode<T>(data);
			if ( children == null )
				children = new HashMap<String, TreeNode<T>>();
			children.put(id, node);
			node.setParent(this);
		}
	}
	public void addChild(TreeNode<T> data, String id){
		synchronized ( this ){
			if ( children == null )
				children = new HashMap<String, TreeNode<T>>();
			children.put(id, data);
			data.setParent(this);
		}
	}
	public void removeChild(TreeNode<T> data){
		synchronized ( this ){
			if ( children != null ) {
				for ( String id : children.keySet() ){
					if ( children.get(id) == data ){
						children.remove(id);
						data.setParent(null);
						return;
					}
				}
			}
		}
	}
	public void removeChild(String id){
		synchronized ( this ){
			if ( children != null ) {
				TreeNode<T> data = children.get(id);
				if ( data != null ) {
					children.remove(id);
					data.setParent(null);
				}
			}
		}
	}
	public void removeAllChildren(){
		synchronized (this) {
			if ( children != null ) {
				for ( String id : children.keySet() ){
					TreeNode<T> node = children.get(id);
					node.setParent(null);
				}
				children.clear();
				children = null;
			}
		}
	}
	public TreeNode<T> getParent(){
		return parent;
	}
	public void setParent(TreeNode<T> parent){
		this.parent = parent;
	}
	public HashMap<String, TreeNode<T>> getChildren(){
		return children;
	}
}